/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: AjaxSupportLoginUrlAuthenticationEntryPoint.java
 * 创  建  人: Roc Zheng (roc.djz@gmail.com)
 * 创建时间: 2017年8月2日 下午3:35:43
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.sys.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;

/**
 * 
 * 
 * @since 1.0
 * @version 1.0
 * @author Roc Zheng (roc.djz@gmail.com)
 */
public class AjaxSupportLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
  private final RedirectStrategy redirectStrategy = new DefaultAjaxRedirectStrategy(); 
  
  /**
   * 初始化 {@link AjaxSupportLoginUrlAuthenticationEntryPoint} 类的新实例。
   */
  public AjaxSupportLoginUrlAuthenticationEntryPoint() {
    super(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL);
  }
  
  /**
   * 
   * 初始化 {@link AjaxSupportLoginUrlAuthenticationEntryPoint} 类的新实例。
   * @param loginFormUrl
   */
  public AjaxSupportLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
    super(loginFormUrl);
  }
  
  /**
   * {@inheritDoc}
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
      throws IOException, ServletException {
    if (isUseForward()) {
      super.commence(request, response, authException);
      return;
    }
    
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    String redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
    redirectStrategy.sendRedirect(request, response, redirectUrl);
  }
}
